#include <iostream>
#include <thread>
#include <mutex>
#include <ctime>
#include <cstdlib>
#include <chrono>

std::mutex medium; // 模拟共享传输介质
const int numNodes = 5; // 节点数量

// 随机退避时间（单位：毫秒）
int backoff() {
    return rand() % 1000; // 简单模拟退避时间
}

// 节点发送数据
void nodeSend(int nodeId) {
    while (true) {
        // 模拟载波监听：尝试获取介质
        if (medium.try_lock()) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟发送数据时间
            std::cout << "Node " << nodeId << " sends data successfully!" << std::endl;
            medium.unlock();
            break;
        } else {
            // 检测到冲突
            std::cout << "Node " << nodeId << " detects collision! Backoff..." << std::endl;
            int delay = backoff();
            std::this_thread::sleep_for(std::chrono::milliseconds(delay));
        }
    }
}

int main() {
    srand(static_cast<unsigned int>(time(nullptr)));
    std::thread nodes[numNodes];

    // 启动多个节点线程
    for (int i = 0; i < numNodes; ++i) {
        nodes[i] = std::thread(nodeSend, i);
    }

    // 等待所有线程结束
    for (int i = 0; i < numNodes; ++i) {
        nodes[i].join();
    }

    return 0;
}